package org.springframework.web.tag;

import org.springframework.web.common.RequestAttrs;
import org.springframework.web.modules.ModuleConfiguration;
import org.springframework.web.tag.templates.ModulePlaceholderTemplate;
import org.springframework.web.tag.templates.ScriptTemplate;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.util.concurrent.ConcurrentHashMap;

import java.util.Map;

/**
 * @author float.lu
 */
public class ModuleTag extends BodyTagSupport{

    private String mapping;

    private boolean sync;

    @Override
    public int doStartTag() throws JspException {


        try {
            pageContext.getRequest().setAttribute(RequestAttrs.CO_MARK, RequestAttrs.CO_MARK);

            Object pageKey = pageContext.getRequest().getAttribute(RequestAttrs.PAGE_KEY);
            if (pageKey == null) {
                throw new RuntimeException("Pagekey missed!");
            }
            Object cfgObj = pageContext.getRequest().getAttribute((String) pageKey);
            if (cfgObj == null) {
                cfgObj = new ConcurrentHashMap();
            }
            Map<String, ModuleConfiguration> mapCfg = (Map) cfgObj;
            mapCfg.put(mapping, ModuleConfiguration.builder().setMapping(mapping)
                    .setSync(sync).build());
            pageContext.getRequest().setAttribute((String) pageKey, mapCfg);

            if (pageContext.getRequest().getAttribute(RequestAttrs.CO_SCRIPT_MARK) == null) {
                pageContext.getOut().write(ScriptTemplate.script);
                pageContext.getRequest().setAttribute(RequestAttrs.CO_SCRIPT_MARK, (ModulePlaceholderTemplate.makePlaceHolder(mapping)));
            }

            pageContext.getOut().write(ModulePlaceholderTemplate.makePlaceHolder(mapping));
        } catch (Exception e) {
            //NO OP
        }
        return super.doStartTag();
    }


    public String getMapping() {
        return mapping;
    }

    public void setMapping(String mapping) {
        this.mapping = mapping;
    }

    public boolean isSync() {
        return sync;
    }

    public void setSync(boolean sync) {
        this.sync = sync;
    }

}
